﻿namespace SharpF2.Components
{
	using System.Windows;
	using System.Windows.Controls;
	using System.Windows.Controls.Primitives;
	using Commands;

	/// <summary>
	/// Interaction logic for ListViewExtended.Sortable
	/// </summary>
	public partial class ListViewExtended<ItemType>
	{
		#region Public Attributes

		public static readonly DependencyProperty SortColumnCommandProperty =
			DependencyProperty.Register(
				"SortColumnCommand",
				typeof (DelegateCommand<GridViewColumnExtension<ItemType>>),
				typeof (ListViewExtended<ItemType>));

		#endregion

		#region Public Properties

		public DelegateCommand<GridViewColumnExtension<ItemType>> SortColumnCommand
		{
			get { return (DelegateCommand<GridViewColumnExtension<ItemType>>) GetValue(SortColumnCommandProperty); }
			set { SetValue(SortColumnCommandProperty, value); }
		}

		#endregion

		#region Private Members

		private void ColumnHeader_Click(object sender, RoutedEventArgs e)
		{
			var headerClicked = e.OriginalSource as GridViewColumnHeader;
			if (headerClicked == null) return;

			var sortedColumn = headerClicked.Column as GridViewColumnExtension<ItemType>;

			if (null == SortColumnCommand) return;

			if (SortColumnCommand.CanExecute(sortedColumn))
				SortColumnCommand.Execute(sortedColumn);
		}

		private void SortableInitialize()
		{
			AddHandler(ButtonBase.ClickEvent, new RoutedEventHandler(ColumnHeader_Click));
		}

		#endregion
	}
}